package com.geek.log4jcontrol.remote;

import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import com.geek.log4jcontrol.proxy.RemoteProxyCglib;
import com.geek.log4jcontrol.remote.impl.Log4jControlRemoteImpl;

/**
 * @package com.geek.log4jcontrol.remote
 * @description 注册RMI接口，启动服务
 * @author Goliath
 * @createTime 2012-8-3 上午09:56:28
 * @modifyTime
 */
public class RmiServer {
	/**
	 * @param ip RMI服务Ip
	 * @param port RMI服务端口
	 * @param rmiName RMI服务名
	 */
	public RmiServer(String ip, int port, String rmiName) {
		try {
			// jdk 自带的代理 只针对接口进行代理，不能用于RMI
			/* Log4jControlRemote oLog4jControlRemote = (Log4jControlRemote)Log4jControlRemoteProxy.factory(new Log4jControlRemoteImpl()); */
			Log4jControlRemote oLog4jControlRemote = (Log4jControlRemoteImpl) new RemoteProxyCglib()
					.getProxy(Log4jControlRemoteImpl.class);
			Naming.rebind("rmi://" + ip + ":" + port + "/" + rmiName, oLog4jControlRemote);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @package com.geek.log4jcontrol.remote
	 * @description 启动RMI的注册服务，并尝试注册端口
	 * @param port RMI服务端口
	 * @return RMI的注册信息
	 * @returnType Registry
	 * @author Goliath
	 * @createTime 2012-8-3 上午10:12:00
	 * @modifyTime
	 */
	public static Registry createRegistry(int port) {
		Registry registry = null;
		try {
			registry = LocateRegistry.getRegistry(port); // 如果该端口未被注册，则抛异常
			registry.list(); // 拿到该端口注册的rmi对象
		} catch (final Exception e) {
			try {
				registry = LocateRegistry.createRegistry(port);// 捕获异常，端口注册
			} catch (final Exception ee) {
				ee.printStackTrace();
			}
		}
		return registry;
	}

}
